package com.tianjipms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianjipms.dao.UserMapper;
import com.tianjipms.entity.User;
import com.tianjipms.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public boolean existsByuserPhone(String phone) {
        return userMapper.exists(new QueryWrapper<User>().eq("phone",phone));
    }

    @Override
    public IPage<User> findUserByRoleIdPage(IPage<User> page, Long roleId) {
        // 查询符合条件的用户列表
        List<User> userList = userMapper.findUserByRoleId(roleId);
        // 查询符合条件的总记录数
        Integer total = userList.size();
        // 设置分页参数
        page.setTotal(total);
        // 将查询结果封装成分页对象并返回
        return new Page<User>(page.getCurrent(), page.getSize(), total).setRecords(userList);
    }

    @Override
    public User findUserByPhone(String phone) {
        //创建条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        //用户名
        queryWrapper.eq("phone",phone);
        //返回查询记录
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveUserRole(Long userId, List<Long> roleIds) {
        //删除该用户对应的角色信息
        userMapper.deleteUserRole(userId);
        //保存用户角色信息
        return baseMapper.saveUserRole(userId,roleIds)>0;
    }
}
